home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news!enno
- From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
- Newsgroups: comp.lang.c++
- Subject: Re: Why use a reference on a ptr foo(int &*parm) as a formal parm ?
- Date: 11 Feb 1996 14:52:18 GMT
- Organization: Fachbereich Informatik, TH Darmstadt
- Distribution: world
- Message-ID: <ENNO.96Feb11155218@kitz.inferenzsysteme.informatik.th-darmstadt.de>
- References: <311DC7A8.2A1C@worldcom.ch>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- In-reply-to: Jean-Pierre Schnyder's message of Sun, 11 Feb 1996 11:40:40 +0100
-
- In article <311DC7A8.2A1C@worldcom.ch> Jean-Pierre Schnyder <jschnyde@worldcom.ch> writes:
-
- I'm not sure to understand the rationale for this technique. Any idea ?
-
- Passing a non-const reference as argument is one way to perform a 'call by
- reference' in C++. Another way is to use a pointer to the appropriate type
- instead. An example might be helpful:
-
- >>>>
- #include <iostream.h>
-
- void alloc(int*& mem,int n) { mem=new int[n]; }
- void dealloc(int* mem) { delete[] mem; }
-
- int main()
- {
- int* ip;
- alloc(ip,100);
- dealloc(ip);
- }
- <<<<
-
- The invocation of 'alloc' modifies the pointer 'ip'. Before the function
- call 'ip' points to nowhere, afterwards it points to the newly allocated
- integer array. If 'alloc' would be defined as
-
- void alloc(int* mem,int n) { mem=new int[n]; }
-
- the local copy of the pointer value would be changed but not 'ip'.
- In contrast 'dealloc' doesn't need a to modify the pointer because it simply
- uses the pointer to free the allocated ressources.
-
- Enno
-
- PS: a pointer to a reference is no valid type in C++.
- --
- Enno
-